package com.my.app.listener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.ContextLoaderListener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 */

public class MyContextLoaderListener extends ContextLoaderListener {

    private final Logger logger = LogManager.getLogger(getClass());

    @Override
    public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized(event);

        ServletContext context = event.getServletContext();
        String serverInfo = context.getServerInfo();
        logger.info("This server info: {}, The resource root path: {}", serverInfo ,this.getClass().getResource("/"));

        InputStream in = null;
        if(serverInfo.contains("Tomcat")){
        	in = context.getResourceAsStream("/WEB-INF/classes/my.properties");
        }
        try {
            String ctx = context.getContextPath();
            context.setAttribute("ctx", ctx);
            if (null == in) {
                in = this.getClass().getResourceAsStream("/my.properties");
            }

            if (in != null) {
                //my properties load
                Properties prop = new Properties();
                prop.load(in);
                String staticPath = prop.getProperty("http.static.path").trim();
                String appName = prop.getProperty("server.name").trim();
                logger.info("static resources path:" + staticPath);

                context.setAttribute("appName", appName);
                context.setAttribute("assets", ctx + staticPath);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
